using System;
using Fadd.Globalization;
#if TEST
using Xunit;
#endif

namespace Fadd.Validation
{
    /// <summary>
    /// Makes sure that only digits have been entered.
    /// </summary>
    /// <para>
    /// Language file items:
    /// <list type="table">
    ///     <listheader>
    ///         <term>ItemName</term>
    ///         <description>Language text</description>
    ///     </listheader>
    ///     <item>
    ///         <term>Digits</term>
    ///         <description>'{0}' may only contain digits.</description>
    ///     </item>
    ///     <item>
    ///         <term>DigitsExtra</term>
    ///         <description>'{0}' may only contain digits and "{1}".</description>
    ///     </item>
    /// </list>
    /// </para>
    public class ValidateDigitsAttribute : ValidateAttribute
    {
        private readonly string _extraChars;

        /// <summary>
        /// Name used in language files.
        /// </summary>
        public const string Name = "Digits";

        /// <summary>
        /// Initializes a new instance of the <see cref="ValidateAttribute"/> class.
        /// </summary>
        public ValidateDigitsAttribute()
        {
            _extraChars = string.Empty;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ValidateAttribute"/> class.
        /// </summary>
        /// <param name="extraChars">extra characters that are valid.</param>
        public ValidateDigitsAttribute(string extraChars)
        {
            Check.NotEmpty(extraChars, "extraChars");
            _extraChars = extraChars;
        }

        /// <summary>
        /// Validate value
        /// </summary>
        /// <param name="context">Can be used to send a context object to the validation class. Useful if you provide your own validation classes which need to get information from your application. <seealso cref="BeforeValidationEventArgs"/></param>
        /// <param name="value">value to validate</param>
        /// <returns>
        /// true if value passed the validation; otherwise false.
        /// </returns>
        public override bool Validate(object context, object value)
        {
            if (IsEmpty(value))
                return true;
            
            if (value is string)
            {
                string s = (string) value;
                foreach (char ch in s)
                {
                    if (char.IsDigit(ch) || _extraChars.IndexOf(ch) != -1)
                        continue;

                    return false;
                }
                return true;
            }

            throw new NotSupportedException(GetType() + " only supports strings.");
        }

        /// <summary>
        /// Localize error if validation failed.
        /// </summary>
        /// <param name="fieldName">Localized field name.</param>
        /// <param name="validationLanguage">Language node with all validation translations.</param>
        /// <returns>A localized error message if the validation failed; otherwise null.</returns>
        /// <example>
        /// <code>
        /// attribute.Localize("FirstName", "'{0}' is required"); 
        /// // will return "'{0}' is required" if the validation failed, else null.
        /// </code>
        /// </example>
        public override string Format(string fieldName, ILanguageNode validationLanguage)
        {
            return string.IsNullOrEmpty(_extraChars) == false
                       ? string.Format(validationLanguage["DigitsExtra"], fieldName, "1234567890" + _extraChars)
                       : string.Format(validationLanguage["Digits"], "1234567890" + fieldName);
        }

        /// <summary>
        /// Determines if the validation class support the specified type.
        /// </summary>
        /// <param name="type">Property/Value type.</param>
        /// <returns>true if the type is supported.</returns>
        public override bool SupportsType(Type type)
        {
            return type == typeof (string);
        }

#if TEST
        [Fact]
        private static void Test()
        {
            ValidateDigitsAttribute a = new ValidateDigitsAttribute();
            Assert.True(a.Validate(null, "0123456789"));
            Assert.False(a.Validate(null, "abc"));
            Assert.False(a.Validate(null, " "));

            a = new ValidateDigitsAttribute("abc");
            Assert.True(a.Validate(null, "0123456789"));
            Assert.True(a.Validate(null, "abc"));
            Assert.False(a.Validate(null, "def"));
        }
#endif

    }
}
